package com.ruoyi.web.controller.shopping;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.shopping.domain.*;
import com.ruoyi.shopping.service.IMallOrderMeshService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.shopping.service.IMallOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.w3c.dom.css.DOMImplementationCSS;


/**
 * 商城订单Controller
 *
 * @author ruoyi
 * @date 2022-06-09
 */
@RestController
@RequestMapping("/shopping/mallOrder")
public class MallOrderController extends BaseController
{
    @Autowired
    private IMallOrderService mallOrderService;
    @Autowired
    private IMallOrderMeshService mallOrderMeshService;


    /**
     * 根据合并订单id查询商品订单信息
     */
    @GetMapping("/getOrderMeshId")
    public TableDataInfo getOrderMeshId(Long id ) {

        MallOrder mallOrder = new MallOrder();
        mallOrder.setMergeOrderId(id);
        List<MallOrder> mallOrderList = mallOrderService.selectOrderList(mallOrder);
        mallOrderList.forEach(e->{
            e.setMergeInformation(e.getProductName()+" "+""+"|"+e.getSpecificationName()+" "+""+e.getPayPrice()+" "+"x"+" "+e.getNum());
        });
        return  getDataTable(mallOrderList);
    }


    /**
     * 商城订单发货
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallOrder:edit')")
    @GetMapping("/editStatus")
    public AjaxResult editStatus(String ids, String deliveryType, String courierCompany, String courierNumber) {

        if (StringUtils.isEmpty(ids)){
            return  AjaxResult.error("没有要选择的商品信息！");
        }
        String[] array =ids.split(",");
        for (String id : array) {
            MallOrder mallOrder = new MallOrder();
            mallOrder.setId(Long.valueOf(id));
            mallOrder.setDeliverytype(deliveryType);
            mallOrder.setCourierCompany(courierCompany);
            mallOrder.setCourierNumber(courierNumber);
            mallOrder.setDeliveryTime(new Date());
            mallOrder.setOrderState(DicConstants.ORDER_STATE_Shipped.getCode());
            if (deliveryType.equals("deliver_goods")){
                mallOrder.setDistributionDmode("N");
            }
            if (deliveryType.equals("no_deliver_goods")){
                mallOrder.setDistributionDmode("Y");
            }
            mallOrderService.updateMallOrder(mallOrder);
        }
        MallOrder mallOrder = mallOrderService.selectMallOrderById(Long.valueOf(array[0]));
        List<MallOrder> mallOrders = mallOrderService.selectMallOrderByMeshId(mallOrder.getMergeOrderId());
        int count = 0;
        for (MallOrder order : mallOrders) {
            if(DicConstants.ORDER_STATE_Shipped.getCode().equals(order.getOrderState())){
                count++;
            }
        }
        if(count == mallOrders.size()){
            MallOrderMesh mallOrderMesh = mallOrderMeshService.selectMallOrderMeshById(mallOrder.getMergeOrderId());
//            mallOrderMesh.setShipState(DicConstants.SYS_Y.getCode());
            mallOrderMesh.setOrderState(DicConstants.ORDER_STATE_Shipped.getCode());
            mallOrderMeshService.updateMallOrderMesh(mallOrderMesh);
        }

        return AjaxResult.success();

    }
    //商城售后修改
    @PreAuthorize("@ss.hasPermi('shopping:mallOrder:edit')")
    @GetMapping("/editOrder")
    public AjaxResult editOrder(Long id ,String status,String refundReason){
        MallOrder mallOrder = new MallOrder();
        mallOrder.setId(id);
        mallOrder.setRefundStatus(status);
        mallOrder.setRefundMoney(mallOrder.getPayPrice());
        if(DicConstants.REFUND_STATUS_Refused.getCode().equals(status)){
            mallOrder.setAfterSalesState(DicConstants.SYS_N.getCode());
        }
        mallOrderService.updateMallOrder(mallOrder);
        if (!StringUtils.isEmpty(refundReason)){
            mallOrder.setRefundRefuseReaso(refundReason);
        }
        MallOrder order1 = mallOrderService.selectMallOrderById(id);
        if(DicConstants.REFUND_STATUS_Pass.getCode().equals(status)){
            mallOrderService.refundPay(mallOrder.getId());
            MallOrderMesh mesh = mallOrderMeshService.selectMallOrderMeshById(order1.getMergeOrderId());
            mesh.setAftersaleState(DicConstants.SYS_Y.getCode());
            mallOrderMeshService.updateMallOrderMesh(mesh);
        }

        List<MallOrder> orders = mallOrderService.selectMallOrderByMeshId(order1.getMergeOrderId());
        int count = 0;
        for (MallOrder order : orders) {
            if (DicConstants.SYS_N.getCode().equals(order.getAfterSalesState())) {
                count++;
            }
        }
        if (count >= orders.size()) {
            MallOrderMesh mallOrderMesh = mallOrderMeshService.selectMallOrderMeshById(order1.getMergeOrderId());
            mallOrderMesh.setAftersaleState(DicConstants.SYS_N.getCode());
            mallOrderMeshService.updateMallOrderMesh(mallOrderMesh);
        }
        mallOrderService.checkFinished(order1.getMergeOrderId());
        return toAjax(1);
    }

    /**
     * 查询商城订单列表
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(MallOrder mallOrder)
    {
        startPage();
        List<MallOrder> mallOrderList = mallOrderService.selectMallOrderList(mallOrder);
        return getDataTable(mallOrderList);
    }

/**
 * 查询商城售后订单列表
 */
    @GetMapping("/listMallAfterSaleOrder")
    public TableDataInfo listMallAfterSaleOrder(MallOrder mallOrder)
    {
        startPage();
        //根据合并订单查询
        if (!StringUtils.isEmpty(mallOrder.getCombineOrder())){
            MallOrderMesh mallOrderMesh = new MallOrderMesh();
            mallOrderMesh.setOrderId(mallOrder.getCombineOrder());
            List<MallOrderMesh> orderMeshes = mallOrderMeshService.selectMallOrderMeshList(mallOrderMesh);
//            orderMeshes.forEach(e->{
//                mallOrder.setMergeOrderId(e.getId());
//            });
            if(orderMeshes.size() == 0)
                return getDataTable(new ArrayList<>());
            mallOrder.setMergeOrderId(orderMeshes.get(0).getId());

        }
        List<MallOrder> list = mallOrderService.selectAfterSaleOrderList(mallOrder);
        List CouponIds =list.stream().map(MallOrder::getMergeOrderId).distinct().collect(Collectors.toList());
        if (CouponIds.size()>0){
            List<MallOrderMesh> orderMeshesId =mallOrderMeshService.selectMallOrderMeshByIds(CouponIds);
            HashMap<Long, String> map = new HashMap<>();
            orderMeshesId.forEach(e->{
                map.put(e.getId(),e.getOrderId());
            });
            list.forEach(e->{
                e.setCombineOrder(map.get(e.getMergeOrderId()));
            });
        }
        return getDataTable(list);
    }



    /**
     * 导出商城订单列表
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallOrder:export')")
    @Log(title = "商城订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MallOrder mallOrder)
    {
        List<MallOrder> list = mallOrderService.selectMallOrderList(mallOrder);
        ExcelUtil<MallOrder> util = new ExcelUtil<MallOrder>(MallOrder.class);
        return util.exportExcel(list, "商城订单数据");
    }

    /**
     * 获取商城订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallOrder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        MallOrder mallOrder = mallOrderService.selectMallOrderById(id);
        mallOrder.setOrderState(DictUtils.getDictLabel("order_state",mallOrder.getOrderState()));//订单状态
        mallOrder.setRefundStatus(DictUtils.getDictLabel("refund_status",mallOrder.getRefundStatus()));//退款状态
//        mallOrder.setRefundReason(DictUtils.getDictLabel("refund_cause",mallOrder.getRefundReason()));//退款原因
        mallOrder.setCommentStatus(DictUtils.getDictLabel("sys_yes_no",mallOrder.getCommentStatus()));//是否已评价
        mallOrder.setDistributionDmode(DictUtils.getDictLabel("sys_distribution_dmode",mallOrder.getDistributionDmode()));//配送方式
        mallOrder.setRefundPayStatus(DictUtils.getDictLabel("sys_yes_no",mallOrder.getRefundPayStatus()));//退款支付状态
        return AjaxResult.success(mallOrder);
    }

    /**
     * 新增商城订单
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallOrder:add')")
    @Log(title = "商城订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MallOrder mallOrder)
    {
        return toAjax(mallOrderService.insertMallOrder(mallOrder));
    }

    /**
     * 修改商城订单
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallOrder:edit')")
    @Log(title = "商城订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MallOrder mallOrder)
    {
        mallOrder.setUpdateType(DicConstants.BUSINESS_Manager.getCode());
        return toAjax(mallOrderService.updateMallOrder(mallOrder));
    }
    /**
     * 平台备注
     */
    @PutMapping("/platformRemark")
    public AjaxResult platformRemark(String  remark,Long id)
    {
        MallOrder mallOrder = new MallOrder();
        mallOrder.setId(id);
        mallOrder.setPlatformRemark(remark);
        return AjaxResult.success( mallOrderService.updateMallOrder(mallOrder));
    }

    /**
     * 删除商城订单
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallOrder:remove')")
    @Log(title = "商城订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mallOrderService.logicDeleteMallOrder(ids,DicConstants.BUSINESS_Manager.getCode(),SecurityUtils.getUserId()));
    }
    @GetMapping("/queryAfterOrderDetail/{id}")
    public AjaxResult queryAfterOrderDetail(@PathVariable Long id)
    {
        HashMap<String, Object> map = new HashMap<>(3);
        MallOrder order = mallOrderService.selectMallOrderById(id);
        JSONObject addrJso = new JSONObject();
        JSONObject meshJso = new JSONObject();
        MallOrderMesh mesh = mallOrderMeshService.selectMallOrderMeshById(order.getMergeOrderId());
        String company = DictUtils.getDictLabel("logistics_company", order.getCourierCompany());
        order.setCourierCompany(company);
        if(DicConstants.SYS_Y.getCode().equals(order.getAfterSalesState())){
            order.setOrderState(DictUtils.getDictLabel("refund_status",order.getRefundStatus()));

        }else if(DicConstants.ORDER_STATE_Wait_Pay.getCode().equals(mesh.getOrderState())){
            order.setOrderState(DicConstants.ORDER_STATE_Wait_Pay.getName());

        }
        genAfterMeshJson(mesh,meshJso,order);
        genAddrInfo(addrJso,order);
        map.put("mesh",meshJso);
        map.put("order",order);
        map.put("addr",addrJso);
        return AjaxResult.success(map);
    }

    private void genAfterMeshJson(MallOrderMesh mesh, JSONObject jso, MallOrder order) {
        jso.put("id", mesh.getId());
        jso.put("orderId",mesh.getOrderId());
        jso.put("payState",mesh.getPayState());
        jso.put("payPrice",mesh.getPayPrice().setScale(2,BigDecimal.ROUND_DOWN).toString());
        jso.put("payTime", DateUtils.dateToStr(mesh.getPayTime()));
        jso.put("createTime",DateUtils.dateToStr(mesh.getCreateTime()));
        jso.put("orderState",DictUtils.getDictLabel("order_state",mesh.getOrderState()));
        jso.put("buyerComment",mesh.getCustomerRemark());
        jso.put("saleComment",mesh.getPlatformRemark());
        jso.put("refundReason",order.getRefundReason());
        jso.put("refundRefuse",order.getRefundRefuseReaso());
        jso.put("refundTime",DateUtils.dateToStr(order.getRefundTime()));
        jso.put("refundPrice",order.getRefundMoney().setScale(2,BigDecimal.ROUND_DOWN).toString());
        jso.put("refundStatus",DictUtils.getDictLabel("refund_status",order.getRefundStatus()));
    }

    @GetMapping("/queryOrderDetail/{id}")
    public AjaxResult queryOrderDetail(@PathVariable Long id)
    {
        HashMap<String, Object> map = new HashMap<>(3);

        MallOrderMesh mesh = mallOrderMeshService.selectMallOrderMeshById(id);
        JSONObject meshJso = new JSONObject();

        List<MallOrder> orders = mallOrderService.selectMallOrderByMeshId(id);
        JSONObject addrJso = new JSONObject();
        BigDecimal deductionPrice = BigDecimal.ZERO;
        BigDecimal totalPrice = BigDecimal.ZERO;
        ArrayList<JSONObject> orderJson = new ArrayList<>();
        for (MallOrder order : orders) {
            JSONObject jso = new JSONObject();
            if(order.getDeductionPrice()!=null){
                deductionPrice = deductionPrice.add(order.getDeductionPrice());
            }
            totalPrice = totalPrice.add(order.getPayPrice());
            jso.put("id",order.getId());
            jso.put("productId",order.getProductId());
            jso.put("productImage",order.getProductImage());
            jso.put("productName",order.getProductName());
            jso.put("specificationName",order.getSpecificationName());
            jso.put("num",order.getNum());
//            jso.put("createTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",order.getCreateTime()));
            jso.put("payPrice",order.getPayPrice().setScale(2,BigDecimal.ROUND_DOWN));
            jso.put("totalPrice",order.getPayPrice().add(order.getDeductionPrice()));
            jso.put("refundStatus",DictUtils.getDictLabel("order_state",order.getRefundStatus()));
            jso.put("orderState",DictUtils.getDictLabel("order_state",order.getOrderState()));
            jso.put("commentStatus",order.getCommentStatus());
            jso.put("courierNumber",order.getCourierNumber()==null?"":order.getCourierNumber());
            jso.put("courierTime",DateUtils.dateToStr(order.getDeliveryTime()));
            String company = DictUtils.getDictLabel("logistics_company", order.getCourierCompany());
            jso.put("courierCompany", company==null?"":company);
            jso.put("mode",order.getDistributionDmode());
            if(DicConstants.SYS_Y.getCode().equals(order.getAfterSalesState())){
                jso.put("orderState",DictUtils.getDictLabel("refund_status",order.getRefundStatus()));

            }else if(DicConstants.ORDER_STATE_Wait_Pay.getCode().equals(mesh.getOrderState())){
                jso.put("orderState",DicConstants.ORDER_STATE_Wait_Pay.getName());
            }
            if(DicConstants.ORDER_STATE_FINISHED.getCode().equals(mesh.getOrderState()) && DicConstants.SYS_N.getCode().equals(mesh.getPayState())){
                jso.put("orderState","已取消");

            }
            orderJson.add(jso);
        }
        genAddrInfo(addrJso,orders.get(0));
        genMeshJson(mesh,meshJso,deductionPrice,totalPrice);
        map.put("mesh",meshJso);
        map.put("order",orderJson);
        map.put("addr",addrJso);

        return AjaxResult.success(map);
    }

    private void genMeshJson(MallOrderMesh mesh, JSONObject jso, BigDecimal deductionPrice, BigDecimal totalPrice) {
        jso.put("id", mesh.getId());
        jso.put("orderId",mesh.getOrderId());
        jso.put("payState",mesh.getPayState());
        jso.put("payPrice",mesh.getPayPrice().setScale(2,BigDecimal.ROUND_DOWN).toString());
        jso.put("deductionPrice",deductionPrice);
        jso.put("payTime", DateUtils.dateToStr(mesh.getPayTime()));
        jso.put("createTime",DateUtils.dateToStr(mesh.getCreateTime()));
        jso.put("totalPrice",totalPrice.add(deductionPrice).setScale(2,BigDecimal.ROUND_DOWN).toString());
        jso.put("orderState",DictUtils.getDictLabel("order_state",mesh.getOrderState()));
        jso.put("buyerComment",mesh.getCustomerRemark());
        jso.put("saleComment",mesh.getPlatformRemark());
    }

    private void genAddrInfo(JSONObject jso, MallOrder mallOrder) {
        jso.put("name",mallOrder.getConsigneeName());
        jso.put("phone",mallOrder.getConsigneePhone());
        jso.put("address",mallOrder.getConsigneeAddress());
    }


}
